package com.wl.cloudzuul.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.wl.bean.Result;
import com.wl.dm.util.JwtUtil;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

@Component
public class LoginFilter extends ZuulFilter {
    @Override  //过滤类型
    public String filterType() {
        return "post";  //后置拦截
    }

    @Override  //过滤顺序
    public int filterOrder() {
        return 0;
    }

    @Override  //是否拦截
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String path = request.getServletPath();
        System.out.println("path = " + path + " => " + path.matches("/[^/]+/login/login"));
        return path.matches("/[^/]+/login/login");
    }

    @Override
    public Object run() throws ZuulException {
        //通过RequestContext这个类的静态方法，获取当前上下文请求对象
        RequestContext ctx = RequestContext.getCurrentContext();
//        String json = ctx.getResponseBody();
        String json = null;
        HttpServletResponse response = ctx.getResponse();
        ObjectMapper mapper = new ObjectMapper();
        try {
            InputStream inputStream = ctx.getResponseDataStream();
            InputStreamReader inputStreamReader =
                    new InputStreamReader(inputStream,"UTF-8");
            char[] chars = new char[1024];
            int cnt = inputStreamReader.read(chars);
            json = new String(chars,0,cnt);
            Result result = mapper.readValue(json, Result.class);//将json转变回Result
            if (result.getCode() == 1) {
                //构建jwt  加密
                String jwt = JwtUtil.createJWT(30, (Map<String, Object>) result.getData());  //指定时间（30分钟）
                ctx.getResponse().addHeader("Authorization", jwt);
            }else {

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //重新将json写入响应对象
        ctx.setResponseBody(json);
        return null;
    }
}
